package com.blog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.entity.Article;
import com.blog.entity.User;
import com.blog.service.ArticleService;
import com.blog.service.UserService;
import com.blog.service.CategoryService;
import com.blog.service.CommentService;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.ArrayList;

@RestController
@RequestMapping("/api/articles")
@CrossOrigin
public class ArticleController {

    private final ArticleService articleService;
    private final UserService userService;
    private final CategoryService categoryService;
    private final CommentService commentService;
    private static final Logger logger = LoggerFactory.getLogger(ArticleController.class);

    public ArticleController(
        ArticleService articleService, 
        UserService userService,
        CategoryService categoryService,
        CommentService commentService) {
        this.articleService = articleService;
        this.userService = userService;
        this.categoryService = categoryService;
        this.commentService = commentService;
    }

    @PostMapping
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<?> createArticle(@RequestBody Article article) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.findByUsername(username);
        article.setUserId(user.getId());
        return ResponseEntity.ok(articleService.createArticle(article));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<?> updateArticle(@PathVariable Long id, @RequestBody Article article) {
        logger.info("收到更新文章请求: ID={}, 文章数据={}", id, article);
        article.setId(id);
        // 明确设置状态为待审核，不管前端是否传递
        article.setStatus(0);
        logger.info("强制设置文章状态为待审核(0)");
        
        // 确保我们有当前用户信息
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.findByUsername(username);
        if (user != null) {
            logger.info("当前用户: ID={}, 用户名={}, 角色={}", user.getId(), user.getUsername(), user.getRole());
            // 确保是文章作者或管理员
            Article existingArticle = articleService.findById(id);
            if (existingArticle != null) {
                logger.info("现有文章: ID={}, 作者ID={}, 状态={}", existingArticle.getId(), 
                          existingArticle.getUserId(), existingArticle.getStatus());
                // 保留原文章的用户ID
                article.setUserId(existingArticle.getUserId());
            }
        }
        Article updatedArticle = articleService.updateArticle(article);
        logger.info("文章更新完成: ID={}, 新状态={}", updatedArticle.getId(), updatedArticle.getStatus());
        return ResponseEntity.ok(updatedArticle);
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<?> deleteArticle(@PathVariable Long id) {
        articleService.deleteArticle(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getArticle(@PathVariable Long id) {
        articleService.incrementViewCount(id);
        return ResponseEntity.ok(articleService.findById(id));
    }

    @GetMapping("/category/{categoryId}")
    public ResponseEntity<?> getArticlesByCategory(
            @PathVariable Long categoryId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<Article> page = new Page<>(current, size);
        IPage<Article> articles = articleService.findByCategory(categoryId, page);
        return ResponseEntity.ok(articles);
    }

    @GetMapping("/user/{userId}")
    @PreAuthorize("hasRole('USER')")
    public ResponseEntity<?> getArticlesByUser(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<Article> page = new Page<>(current, size);
        IPage<Article> articles = articleService.findByUser(userId, page);
        return ResponseEntity.ok(articles);
    }

    @GetMapping
    public ResponseEntity<?> getAllArticles(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) Long categoryId) {
        logger.info("获取文章列表: current={}, size={}, status={}, categoryId={}", current, size, status, categoryId);
        Page<Article> page = new Page<>(current, size);
        logger.info("创建分页对象: current={}, size={}", page.getCurrent(), page.getSize());
        IPage<Article> articles = articleService.findAll(page, status, null, categoryId);
        logger.info("返回分页结果: total={}, pages={}, size={}, current={}", 
                  articles.getTotal(), articles.getPages(), articles.getSize(), articles.getCurrent());
        return ResponseEntity.ok(articles);
    }

    @GetMapping("/manage")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<?> getManagedArticles(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Integer status) {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.findByUsername(username);
        Long userId = null;
        if (user != null && !"ADMIN".equals(user.getRole())) {
            userId = user.getId();
        }
        IPage<Article> articles = articleService.findAll(new Page<>(current, size), status, userId, null);
        return ResponseEntity.ok(articles);
    }

    @PutMapping("/{id}/status")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateArticleStatus(
            @PathVariable Long id,
            @RequestParam Integer status) {
        articleService.updateStatus(id, status);
        return ResponseEntity.ok().build();
    }
    
    @GetMapping("/dashboard")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getDashboardData() {
        logger.info("获取仪表盘数据开始");
        try {
            // 获取文章总数
            long totalArticles = articleService.count(null);
            logger.info("文章总数: {}", totalArticles);
            
            // 获取待审核文章数量
            long pendingArticles = articleService.count(0);
            logger.info("待审核文章数量: {}", pendingArticles);
            
            // 获取已发布文章数量
            long publishedArticles = articleService.count(1);
            logger.info("已发布文章数量: {}", publishedArticles);
            
            // 获取被拒绝文章数量
            long rejectedArticles = articleService.count(2);
            logger.info("被拒绝文章数量: {}", rejectedArticles);
            
            // 获取用户总数
            long totalUsers = userService.getUserCount();
            logger.info("用户总数: {}", totalUsers);
            
            // 获取分类总数
            long totalCategories = categoryService.getCategoryCount();
            logger.info("分类总数: {}", totalCategories);
            
            // 获取评论总数
            long totalComments = commentService.getCommentCount();
            logger.info("评论总数: {}", totalComments);
            
            // 获取文章访问量TOP5
            List<Map<String, Object>> topArticles = articleService.findTopViewedArticles(5);
            logger.info("热门文章数量: {}", topArticles.size());
            
            // 获取各分类文章统计
            List<Map<String, Object>> categoryStats = articleService.getCategoryArticleStats();
            logger.info("分类统计数量: {}", categoryStats.size());
            
            // 返回统计数据
            Map<String, Object> dashboardData = new HashMap<>();
            dashboardData.put("totalArticles", totalArticles);
            dashboardData.put("pendingArticles", pendingArticles);
            dashboardData.put("publishedArticles", publishedArticles);
            dashboardData.put("rejectedArticles", rejectedArticles);
            dashboardData.put("totalUsers", totalUsers);
            dashboardData.put("totalCategories", totalCategories);
            dashboardData.put("totalComments", totalComments);
            dashboardData.put("topArticles", topArticles);
            dashboardData.put("categoryStats", categoryStats);
            
            logger.info("仪表盘数据获取完成");
            return ResponseEntity.ok(dashboardData);
        } catch (Exception e) {
            logger.error("获取仪表盘数据失败", e);
            return ResponseEntity.status(500).body("获取仪表盘数据失败: " + e.getMessage());
        }
    }
} 